home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7354 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: camelot.dsccc.com!not-for-mail
  2. From: kcline@sun152.spd.dsccc.com (Kevin Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Why Do Return Values Sometimes Have '&' Appended?
  5. Date: 22 Feb 1996 15:37:07 -0600
  6. Organization: DSC Communications Corporation Switch Products Division
  7. Message-ID: <4ginm3$npa@sun152.spd.dsccc.com>
  8. References: <4ggciv$iq1@alcor.usc.edu> <4gh3tb$l7n@qualcomm.com>
  9. NNTP-Posting-Host: sun152.spd.dsccc.com
  10.  
  11. In article <4gh3tb$l7n@qualcomm.com>,
  12. Nasser Abbasi <x!news.be.innet.net!INbe.net!usenet> wrote:
  13. >In article <4ggciv$iq1@alcor.usc.edu>, wawda@alcor.usc.edu (Abu Wawda) says:
  14. >>
  15. >>I have seen code where some of the functions are returned with the
  16. >>reference operator (&) attached to the end. Here is an example:
  17. >>
  18. >>MyReturn& MyFunction(...)
  19. >>{
  20. >>}
  21. >>
  22. >>I don't understand what that does.
  23. >
  24. >...
  25.  
  26. >One possibility is that MyFunction internally has a hidden static
  27. >object of type MyReturn that processing is done on, then finaly
  28. >a reference to it is returned. 
  29. >
  30.  
  31. In general, this is a bad idea.  Such code is automatically NOT
  32. thread-safe.  If the internal object is used to hold data from call to
  33. call, that is even worse; each user of the function must be careful
  34. somehow not to break some other user.  In general objects should hold
  35. state, not functions.
  36.  
  37. Of course, the same holds for class static data as well.
  38.  
  39. However, it is fine for a function to return a reference to one
  40. of it's arguments, e.g.
  41.  
  42.     ostream& operator<<(ostream& o, const SomeClass& obj) {
  43.         ...
  44.         return o;
  45.     }
  46.  
  47. It is also common for a member function to return a reference to *this, 
  48. e.g.
  49.  
  50.     SomeClass::operator=(const SomeClass&) {
  51.       ...
  52.       return *this;
  53.     }
  54.  
  55.  
  56. -- 
  57. Kevin Cline
  58.